package com.fk.regimen;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;


import com.fk.util.CircleImageView;
import com.fk.util.FileUtils;
import com.fk.util.Net;
import com.fk.util.StringUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class EssentialInfo extends Activity implements OnClickListener{
	
//	private String webPath = Net.getIP(EssentialInfo.this);
	
	private CircleImageView img_circle;
	private RadioGroup radioGroup;
	private RadioButton[] radioButtons = new RadioButton[2];
	private EditText et_nickname;
	private EditText et_birth;//计算出生日期
	private Button btn_essentialInfo;
	String tag = "china";
	
	int sexnum;
	String sex;
	String nickname;
	String birthday;
	
	private static final int TAKE_PICTURE = 0x000000;//拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;//从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;//结果
	private static final int AGREE_POST = 4;

	File tempFile = getFileName();
	
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.essentialinfo);
        
        initView();
        
        
    }

	private void initView() {
		img_circle = (CircleImageView) findViewById(R.id.img_circle);
		
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		radioButtons[0] = (RadioButton) findViewById(R.id.radio_man);
		radioButtons[1] = (RadioButton) findViewById(R.id.radio_woman);
		et_nickname = (EditText) findViewById(R.id.et_nickname);
		et_birth = (EditText) findViewById(R.id.et_birth);
		btn_essentialInfo = (Button) findViewById(R.id.btn_essentialInfo);
		
		img_circle.setOnClickListener(this);//点击设置头像
		
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				for(int i=0;i<2;i++){
					if(radioButtons[i].isChecked() == true){
						sexnum = i;
					}
				}
				if(sexnum == 0){
					sex = "男";
				}else{
					sex = "女";
				}
			}
		});
		
		//设置生辰的控件
		et_birth.setOnClickListener(this);
		btn_essentialInfo.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.img_circle:
			//点击选择头像
//			Toast.makeText(EssentialInfo.thaais, "选择头像啦", Toast.LENGTH_SHORT).show();
			// 弹出选择照片来源的对话框
			new PopupWindows(EssentialInfo.this, img_circle);
			
			break;
		case R.id.et_birth:
			//弹出日期选择控件
//			Toast.makeText(this, "要弹出对话框吗？", Toast.LENGTH_LONG).show();
			final Calendar birth = Calendar.getInstance();
			final DatePickerDialog birthDialog = new DatePickerDialog(EssentialInfo.this, new 
					DatePickerDialog.OnDateSetListener() {
						
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							birth.set(year, monthOfYear, dayOfMonth);
							et_birth.setText(DateFormat.format("yyy-MM-dd", birth));
							
						}
					}, birth.get(Calendar.YEAR), birth.get(Calendar.MONTH), 
					birth.get(Calendar.DAY_OF_MONTH));
			
			birthDialog.setTitle("选择生辰");
			
							birthDialog.show();
			
			
			break;
			
		case R.id.btn_essentialInfo:
			//点击“填好了”按钮
			nickname = et_nickname.getText().toString().trim();
			birthday = et_birth.getText().toString().trim();
			if(!StringUtil.isNullOrEmpty(sex) && !StringUtil.isNullOrEmpty(nickname) && !StringUtil.isNullOrEmpty(birthday)){
				HttpUtils httpUtils = new HttpUtils();
				
				
				RequestParams params = new RequestParams();
				params.addBodyParameter("flag", "requiredInfo");
				if(sex.equals("男")){
					params.addBodyParameter("sex", 1+"");
				}else{
					params.addBodyParameter("sex", 2+"");
				}
//				params.addBodyParameter("sex", sex);
				
				params.addBodyParameter("nickname", nickname);
				params.addBodyParameter("birthday", birthday);
				
				
				//传图片
				params.addBodyParameter("tempFile",tempFile);
				
				String webPath = Net.getIP(EssentialInfo.this);
				//webPath+"UserActServlet"
				//http://192.168.191.3:8080/api/test/mytest
				httpUtils.send(HttpMethod.POST,webPath+"UserActServlet", params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						Log.e(tag, "木成功"+arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						Log.e(tag, "成功了"+arg0.result);
						Log.e(tag, "性别是:"+sex);
						//将用户名、密码存入偏好设置
						SharedPreferences preferences = getSharedPreferences("user_pref", MODE_PRIVATE);
						Editor editor = preferences.edit();
						
						//存入数据
						editor.putString("sex", sex);
						editor.putString("nickname", nickname);
						editor.putString("birthday", birthday);
						//提交修改
						editor.commit();
						
						//跳转到欢迎启动页面
						Intent intent = new Intent(EssentialInfo.this,PausePageActivity.class);
						startActivity(intent);
					}
				});
				
				
			}else{
				Toast.makeText(this, "请将信息补充完整", Toast.LENGTH_SHORT).show();
			}
			
			
			break;

		default:
			break;
		}
		
	}
	
	
	
	//弹出选择照片的底部对话框
	public class PopupWindows extends PopupWindow {
		
		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.MATCH_PARENT);
			setHeight(LayoutParams.MATCH_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);//拍照
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);//从相册选择
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);//取消
			bt1.setOnClickListener(new android.view.View.OnClickListener() {
				public void onClick(View v) {
					dismiss();

					Intent openCameraIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					// 指定调用相机拍照后照片的储存路径
					openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(tempFile));

					startActivityForResult(openCameraIntent, TAKE_PICTURE);

				}
			});
			bt2.setOnClickListener(new android.view.View.OnClickListener() {
				public void onClick(View v) {

					dismiss();
					Intent intent = new Intent(
							"android.intent.action.GET_CONTENT");
					intent.setDataAndType(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							"image/*");
					// intent.putExtra("crop", true); //比例什么的
					// intent.putExtra("scale", true); // 启动这个意图

					startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
				}
			});
			bt3.setOnClickListener(new android.view.View.OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
		

	}
	
	
	//需要重写的方法
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == EssentialInfo.RESULT_CANCELED) {// 取消
			return;
		}

		switch (requestCode) {
		case TAKE_PICTURE:
			// 裁剪图片
			startPhotoZoom(Uri.fromFile(tempFile), 500);
			// //裁剪图片
			// fbtn_image.setImageBitmap(bitmap);
			// fbtn_image.getBackground().setAlpha(0);
			break;

		case PHOTO_REQUEST_GALLERY:
			// imguri = data.getData();
			if (data != null)
				startPhotoZoom(data.getData(), 500);
			Log.e(tag, "从相册中选取照片");
			break;

		case PHOTO_REQUEST_CUT:

			
			if (data != null) {
				Log.i("data", "data222--->" + data);
				System.out.println("data222----->" + data);
				setPicToView(data);
			}

			break;
		}
	}
	
	
	// 显示图片
		private void setPicToView(Intent data) {
			// TODO Auto-generated method stub

			Bundle bundle = data.getExtras();
			if (bundle != null) {
				// Bitmap photo=bundle.getParcelable("data");
				Bitmap photo = bundle.getParcelable("data");
				Log.e(tag, "photo:"+photo);

				
				//将裁剪后的图片保存到sdcard上
				String formatTime = StringUtil.getDataTime("yyyyMMddHHmmss");
				boolean y = FileUtils.bitmapToFile(photo, FileUtils.getSDCardPath()
						+ "/regimenImage/" + formatTime + ".jpg");
				
				Log.e(tag, "到底是"+y);
				tempFile = FileUtils.getSaveFile("regimenImage", formatTime
						+ ".jpg");
				
				Drawable drawable = new BitmapDrawable(photo);

				// fbtn_image3.setBackground(drawable);
				 img_circle.setImageBitmap(photo);
//				img_circle.setImageDrawable(drawable);
				
			}

		}
	
		// 裁剪图片
		private void startPhotoZoom(Uri uri, int size) {
			// TODO Auto-generated method stub
			// Toast.makeText(MainActivity.this, "裁剪图片", Toast.LENGTH_LONG).show();
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, "image/*");
			// intent.putExtra("scale", true); //比例什么的
			// crop为true是设置在开启intent中设置显示的view可以裁剪
			intent.putExtra("crop", "true");

			// aspectX aspectY是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);

			// outputX outputY是裁剪图片的宽高
			intent.putExtra("outputX", size);
			intent.putExtra("outputY", size);
			
			//设置是否返回数据
			intent.putExtra("return-data", true);
			// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			// //传递一个参数，就是资源照完照片后照片的导出存放路径

			startActivityForResult(intent, PHOTO_REQUEST_CUT);

		}
	
	
		// 创建一个以当前时间为名称的文件
		private File getFileName() {
			File file = new File(Environment.getExternalStorageDirectory(),
					DateFormat.format("yyyyMMdd_hhmmss",
							Calendar.getInstance(Locale.CHINA))
							+ ".jpg");
			// file.mkdirs();//??
			// String fileName = file.getPath();

			return file;
		}

}
